package com.quick.send.contact.activity;

import java.util.List;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.quick.send.contact.model.Contact;
import com.quick.send.contact.model.ContactCustomAdapter;
import com.quick.send.contact.util.DataHolder;

public class SelectContactsActivity extends QuickActivity {

	ListView listView;
	List<Contact> contactItemList;
	ContactCustomAdapter adapter;
	/** The view to show the ad. */
	private AdView adView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_contact_activity);
		// Create an ad.
		adView = (AdView) this.findViewById(R.id.adView);
		if (isNetworkConnected()) {			
			AdRequest adRequest = new AdRequest.Builder().build();
			adView.loadAd(adRequest);
		} else {
			adView.setVisibility(View.GONE);
		}

		// Get list all contacts
		if (DataHolder.getInstance().getListContactData() == null) {
			DataHolder.getInstance().setListContactData(
					this.loadContactListData());
		}
		this.handleListViewSelectContact();
		this.handleAction();
		// Keep the selected contacts
		this.showCurrentSelectedContactWhenBack();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.quick, menu);
		return true;
	}

	private void handleListViewSelectContact() {
		listView = (ListView) findViewById(R.id.contactListView);
		contactItemList = DataHolder.getInstance().getListContactData();
		adapter = new ContactCustomAdapter(this, contactItemList);
		listView.setAdapter(adapter);
		// handle filter
		listView.setTextFilterEnabled(true);
		EditText filterText = (EditText) findViewById(R.id.filterContactText);
		filterText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

				adapter.getFilter().filter(s);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

	}

	private void handleAction() {
		// Handle button cancel and done
		ImageView imgCancel = (ImageView) findViewById(R.id.imgCancelSelect);
		imgCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				clearSharedPreferences();
				finish();

			}
		});

		ImageView imgDoneSelect = (ImageView) findViewById(R.id.imgDoneSelect);
		imgDoneSelect.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Store selected contacts and go to next screen
				storeSelectedContacts();
				// Go to next screen
				Intent intent = new Intent(SelectContactsActivity.this,
						SelectReceiversActivity.class);
				startActivity(intent);
				// Finish this activity
				finish();

			}
		});

	}

	private void storeSelectedContacts() {

		StringBuffer listContactInfoToStore = new StringBuffer();
		StringBuffer listContactIdToStore = new StringBuffer();

		for (Contact contact : adapter.getOriginalContactList()) {
			if (contact.isSelected()) {
				contact.setMobileNumbers(getPhoneNumber(contact.getContactId()));
				contact.setEmails(getEmailAddress(contact.getContactId()));
				listContactInfoToStore.append(contact.getInfo() + "\n\n");
				listContactIdToStore.append(contact.getContactId() + ";");
			}
		}
		SharedPreferences preferencesSelectedContacts = getSharedPreferences();
		Editor editor = preferencesSelectedContacts.edit();
		editor.putString(PREFS_SELECTED_CONTACTS,
				listContactInfoToStore.toString());
		editor.putString(PREFS_SELECTED_CONTACT_IDS,
				listContactIdToStore.toString());
		editor.commit();
	}

	private void showCurrentSelectedContactWhenBack() {
		SharedPreferences sharedPreferences = getSharedPreferences();
		// Get selected contacts
		String selectedContactIds = sharedPreferences.getString(
				PREFS_SELECTED_CONTACT_IDS,
				getResources().getString(R.string.no_contact_found));

		if (!selectedContactIds.equals("")
				&& !selectedContactIds.equalsIgnoreCase(getResources()
						.getString(R.string.no_contact_found))) {

			String[] listIDs = selectedContactIds.split(";");

			for (Contact contact : adapter.getOriginalContactList()) {
				for (String contactID : listIDs) {
					if (contact.getContactId().equals(contactID)) {
						contact.setSelected(true);
					}
				}
			}

		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		clearSharedPreferences();
	}

	@Override
	public void onResume() {
		super.onResume();
		if (adView != null) {
			adView.resume();
		}
	}

	@Override
	public void onPause() {
		if (adView != null) {
			adView.pause();
		}
		super.onPause();
	}

	@Override
	public void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		super.onDestroy();
	}

}
